﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.DynamicData.ModelProviders;
using NHibernate.Mapping;
using Mpu.NHibernateDataModelProvider.ColumnProviders;

namespace Mpu.NHibernateDataModelProvider.AssociationProviders
{
    public class NHibernateOneToManyAssociationProvider : AssociationProvider
    {
        public NHibernateOneToManyAssociationProvider(ColumnProvider columnProvider, OneToMany element)
            : base()
        {
            this.Direction = AssociationDirection.OneToMany;
            this.FromColumn = columnProvider;
            this.IsPrimaryKeyInThisTable = true;

            var toTable = columnProvider.Table.DataModel.Tables.First(t => t.Name == ((Column)element.ColumnIterator.First()).Value.Table.Name);

            var manytooneColumns = toTable.Columns.Where(c => c is NHibernateManyToOneColumnProvider).Cast<NHibernateManyToOneColumnProvider>().ToList();

            this.ToColumn = manytooneColumns.First(c => c.AssociatedTypeName == columnProvider.Table.EntityType.FullName);
        }
    }
}
